import request from "@/utils/request";
import { systemAppStore } from "@/stores/system";
import { userAppStore } from "@/stores/user";
import { parseTime } from "@/utils";

export type ConfigRes<T> = {
  params: T
}

/**
 * 获取配置数据
 * @param {String} c 推广位标识
 * @param {Object} param1
 * @param {Boolean} param1.isCache 是否缓存 默认true; 当设置false时,isForceFlush将被修改为true
 * @param {Boolean} param1.isForceFlush 是否拉取最新
 * @param {Number} param1.expireInterval 缓存时长
 * @param {String} param1.Language 指定配置数据语言
 * @returns Promise 返回配置数据
 */
export function requestConfig(c: string, ops?: {
  isCache?: boolean,
  expireInterval?: number,
  Language?: string,
  isForceFlush?: boolean
}) {
  const { isCache = true, expireInterval, Language } = ops || {};
  let { isForceFlush = false } = ops || {};
  return new Promise(function (resolve) {
    const storageName = "config_" + c;
    let data;
    if (!isCache) {
      isForceFlush = true;
    }
    if (!isForceFlush) {
      data = localStorage.getItem(storageName);
      try {
        if (data) data = JSON.parse(data);
      } catch (e) {
        data = null;
      }
    }
    resolve({ storageName, data });
  }).then(({ storageName, data }: any) => {
    return new Promise(function (resolve, reject) {
      const { version, channel, appID } = systemAppStore().appInfo;
      const appid = appID;
      if (
        data &&
        data.data &&
        data.appid === appid &&
        data.version === version &&
        Language === data.Language &&
        Number(data.expire || 0) &&
        +new Date(Number(data.expire)) > Date.now()
      ) {
        resolve(data.data);
        return;
      }
      const params: any = {
        app_id: appid,
        version,
        keyname: c
      };
      if (channel) {
        params.union_id = channel;
      }
      const headers: any = {
        "Content-Type": "application/json"
      };
      if (Language) {
        headers["Language"] = Language;
      }
      request({
        baseURL: import.meta.env.VITE_APP_CONFIG_API,
        url: "/api/v1/cs/configdata",
        method: "get",
        headers,
        noTestCode: true,
        noMsg: true,
        noAppId: true,
        noToken: true,
        params
      })
        .then((res: any) => {
          if (!res || res.code) {
            return reject();
          }
          if (isCache) {
            const nowTime = Date.now();
            const expireTime = nowTime + (expireInterval || 60 * 60 * 2 * 1000);
            const obj: any = {
              data: res,
              time: nowTime,
              expire: expireTime,
              version,
              appid
            };
            if (Language) {
              obj["Language"] = Language;
            }
            localStorage.setItem(storageName, JSON.stringify(obj));
          }
          resolve(res);
        })
        .catch(reject);
    });
  });
}

/**
 * 检测推广位是否符合[生效时间][关闭弹出][会员]条件
 * @param {Object} param0.configItem
 * @param {Number} param0.nowTime
 * @param {Object} param0.fytgwCloseItem
 * @param {Object} param0.userInfo
 * @param {Object} param0.installDate
 */
export function checkTwgShow({
  configItem,
  nowTime,
  fytgwCloseItem,
  userInfo,
  installDate
}: any) {
  return (
    checkConfigTime(configItem) &&
    checkConfigShow({ configItem, nowTime, fytgwCloseItem }) &&
    checkConfigUser({ configItem, nowTime, userInfo, installDate })
  );
}

/**
 * 检测是否在有效时间内
 * @param {String} param0.start_time
 * @param {String} param0.end_time
 */
export function checkConfigTime({ start_time, end_time }: any) {
  if (!start_time || !end_time) return false;
  const now_time = Date.now();
  start_time = new Date(
    parseTime(start_time, "{y}/{m}/{d} {h}:{i}:{s}") as any
  ).getTime();
  end_time = new Date(parseTime(end_time, "{y}/{m}/{d} {h}:{i}:{s}") as any).getTime();
  return (
    start_time && end_time && start_time <= now_time && end_time >= now_time
  );
}

/**
 * 检测是否符合关闭再弹出条件
 * @param {Number} configItem.times
 * @param {Number} configItem.time_interval
 * @param {Number} nowTime
 * @param {Object} fytgwCloseItem
 */
export function checkConfigShow({
  configItem: { times, time_interval },
  nowTime,
  fytgwCloseItem
}: any) {
  if (fytgwCloseItem) {
    const { time, count } = fytgwCloseItem;
    if (typeof times === "number" && count >= times) {
      return false;
    }
    if (
      typeof time_interval === "number" &&
      time + time_interval * 60 * 1000 > nowTime
    ) {
      return false;
    }
  }
  return true;
}

/**
 * 检测是否符合登录/会员条件
 * @param {Number} configItem.login
 * @param {Number} configItem.user_type
 * @param {Object} configItem.user_type_ex
 * @param {Number} nowTime
 * @param {Object} userInfo
 */
export function checkConfigUser({
  configItem: { login, user_type, user_type_ex },
  nowTime,
  userInfo = {},
  installDate,
}: any) {
  const { register_time } = userInfo;
  // 登录条件
  if (login === 1 && !userInfo.user_id) {
    return false;
  }
  if (login === 0 && userInfo.user_id) {
    return false;
  }

  // 付费状态条件
  if (typeof user_type_ex?.never_vip === "boolean") {
    if (user_type_ex.never_vip && userInfo.has_buy) {
      return false;
    }
    if (!user_type_ex.never_vip && !userInfo.has_buy) {
      return false;
    }
  }

  // 会员相关条件
  const memExpireAt = userInfo.buy_right_package?.[0]?.expire_at || "";
  if (user_type === 1) {
    // 会员
    if (!userInfo.is_member) {
      return false;
    }
    if (user_type_ex?.formal_vip) {
      if (!memExpireAt) {
        return false;
      }
      const { start_before_expire, end_before_expire } =
        user_type_ex.formal_vip;
      if (typeof start_before_expire === "number") {
        const sTime = new Date(memExpireAt);
        sTime.setDate(sTime.getDate() - start_before_expire);
        // eslint-disable-next-line max-depth
        if (nowTime < sTime) {
          return false;
        }
      }
      if (typeof end_before_expire === "number") {
        const eTime = new Date(memExpireAt);
        eTime.setDate(eTime.getDate() - end_before_expire);
        // eslint-disable-next-line max-depth
        if (nowTime > eTime) {
          return false;
        }
      }
    }
  } else if (user_type === 0) {
    // 非会员
    if (userInfo.is_member) {
      return false;
    }
    if (user_type_ex?.formal_vip) {
      if (!memExpireAt) {
        return false;
      }
      const { start_after_expire, end_after_expire } = user_type_ex.formal_vip;
      if (typeof start_after_expire === "number") {
        const sTime = new Date(memExpireAt);
        sTime.setDate(sTime.getDate() + start_after_expire);
        // eslint-disable-next-line max-depth
        if (nowTime < sTime) {
          return false;
        }
      }
      if (typeof end_after_expire === "number") {
        const eTime = new Date(memExpireAt);
        eTime.setDate(eTime.getDate() + end_after_expire);
        // eslint-disable-next-line max-depth
        if (nowTime > eTime) {
          return false;
        }
      }
    }
  }

  // 注册条件
  if (!checkTimeRange(user_type_ex?.register, nowTime, register_time)) {
    return false;
  }

  // 安装条件
  if (!checkTimeRange(user_type_ex?.install, nowTime, installDate)) {
    return false;
  }

  return true;
}
/** 检测是否在时间范围内 */
export function checkTimeRange(range: { start_expire?: number, end_expire?: number }, nowTime: number | Date, time: number | Date){
  if(range){
    if(!time){
      return false
    }
    const { start_expire, end_expire } = range
    if(typeof start_expire === 'number'){
      const sTime = new Date(time)
      sTime.setDate(sTime.getDate() + start_expire)
      if(nowTime < sTime){
        return false
      }
    }
    if(typeof end_expire === 'number'){
      const eTime = new Date(time)
      eTime.setDate(eTime.getDate() + end_expire)
      if(nowTime > eTime){
        return false
      }
    }
  }
  return true
}